package repo

import (
	"storeManageApi/models/dbModels"
	"storeManageApi/models/dbModels/reflectDbModels"
	"xorm.io/builder"
)

// IGoodsConfigRepo
// @Description: 物品配置表操作接口
type IGoodsConfigRepo interface {
	GetPage(start, pageSize int) ([]dbModels.GoodsConfigs, error)
	GetGoodsConfigByUid(uid string) (dbModels.GoodsConfigs, error)
	AddRow(row dbModels.GoodsConfigs) (int64, error)
	GetCount() (int64, error)
	GetAll() ([]dbModels.GoodsConfigs, error)
}

// CreateGoodsConfigRepo
//
//	@Description: 创建物品配置表的Repo
//	@return: IGoodsConfigRepo
func CreateGoodsConfigRepo() IGoodsConfigRepo {
	var goodsConfigTable reflectDbModels.GoodsConfigsTable = reflectDbModels.GetGoodsConfigsTable()
	return &GoodsConfigRepo{
		GoodsConfigTable: goodsConfigTable,
	}
}

// GoodsConfigRepo
// @Description:
type GoodsConfigRepo struct {
	GoodsConfigTable reflectDbModels.GoodsConfigsTable
}

func (repo GoodsConfigRepo) GetAll() ([]dbModels.GoodsConfigs, error) {
	var results []dbModels.GoodsConfigs = make([]dbModels.GoodsConfigs, 0)
	err := Engin.Table(repo.GoodsConfigTable.Table).Find(&results)
	return results, err
}

func (repo GoodsConfigRepo) GetCount() (int64, error) {
	return Engin.Table(repo.GoodsConfigTable.Table).Count()
}

// AddRow
//
//	@Description: 添加一条物品配置
//	@receiver: repo
//	@param: row
//	@return: int64
//	@return: error
func (repo GoodsConfigRepo) AddRow(row dbModels.GoodsConfigs) (int64, error) {
	return Engin.InsertOne(row)
}

// GetGoodsConfigByUid
//
//	@Description: 按照uid获取物品配置
//	@receiver: repo
//	@param: uid
//	@return: dbModels.GoodsConfigs
//	@return: error
func (repo GoodsConfigRepo) GetGoodsConfigByUid(uid string) (dbModels.GoodsConfigs, error) {
	var result dbModels.GoodsConfigs = dbModels.GoodsConfigs{}
	state, err := Engin.Table(repo.GoodsConfigTable.Table).Where(builder.Eq{
		repo.GoodsConfigTable.Base.Uid: uid,
	}).Get(&result)
	if !state || err != nil {
		return dbModels.GoodsConfigs{}, err
	}
	return result, nil
}

// GetPage
//
//	@Description: 分页获取配置表数据
//	@receiver: repo
//	@param: start
//	@param: pageSize
//	@return: []dbModels.GoodsConfigs
//	@return: error
func (repo GoodsConfigRepo) GetPage(start, pageSize int) ([]dbModels.GoodsConfigs, error) {
	var results []dbModels.GoodsConfigs = make([]dbModels.GoodsConfigs, 0)
	err := Engin.Table(repo.GoodsConfigTable.Table).Desc(repo.GoodsConfigTable.Base.Id).Limit(pageSize, start-1).Find(&results)
	return results, err
}
